package com.hellogood.yaohuo.server.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.hellogood.yaohuo.server.db.DBConnection;
import com.hellogood.yaohuo.server.db.DBHelper;
import com.hellogood.yaohuo.shared.entity.Log;
import com.hellogood.yaohuo.shared.exception.DatabaseException;

public class LogDAO extends DBHelper {
	private Logger log = Logger.getLogger(this.getClass());

	@Override
	public List<?> initializeObject(ResultSet rs) throws SQLException {
		List<Log> list = new ArrayList<Log>();
		if (rs != null) {
			while (rs.next()) {
				Log log = new Log();
				log.setLogId(rs.getInt("logID"));
				log.setStaffCode(rs.getString("StaffCode"));
				log.setStaffName(rs.getString("StaffName"));
				log.setLogDate(rs.getString("LogDate"));
				log.setContent(rs.getString("content"));
				list.add(log);
			}
		}
		return list;
	}

	public String addNewLog(Log log) {
		String staffCode = log.getStaffCode() == null ? "" : log.getStaffCode();
		String staffName = log.getStaffName() == null ? "" : log.getStaffName();
		String sql = "INSERT INTO log(logID,staffCode,staffName,logDate,content) VALUES(" + log.getLogId() + ",'" + staffCode + "','" + staffName
				+ "','" + log.getLogDate() + "','" + log.getContent() + "')";
		try {
			if (super.execute(sql) > 0) {
				return "";
			}
		} catch (DatabaseException e) {
			e.printStackTrace();
			this.log.error(e.getMessage());
			return e.getMessage();
		}
		return "";
	}

	@SuppressWarnings("unchecked")
	public List<Log> getLogByPage(int page, int numOfPage) {
		int start = page * numOfPage;
		int end = (page + 1) * numOfPage;
		String sql = "select top " + end + " * from log where logID not in (select top " + start
				+ " logID from log order by logID DESC) order by logID DESC";
		List<?> list = super.query(sql);
		return (List<Log>) list;
	}

	public int getLastLogNo() {
		String sql = "SELECT top 1 logID FROM log order by logID desc";
		int lastLogNo = 0;
//		Connection conn = ConnectionPool.getInstance().getConnection();
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			 conn = DBConnection.getInstance().getConnection();
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			while (rs.next()) {
				lastLogNo = rs.getInt("logID");
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			log.error(ex.getMessage());
		} finally {
			if (rs != null) {
				try {
					rs.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if (ps != null) {
				try {
					ps.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if (conn != null) {
//				ConnectionPool.getInstance().release(conn);
			}
		}
		return lastLogNo;
	}
}
